#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <string>
// ./tcp_client target_port target_ip
void static Usage(char* proc)
{
    std::cout<<"\nUsage"<<proc<<"target_port"<<" "<<"target_ip"<<std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    uint16_t target_port = atoi(argv[2]);
    std::string target_ip = argv[1];
    std::string line;

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cerr << "create socket fail" << std::endl;
        exit(2);
    }

    std::cout << "create socket success" << std::endl;
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(target_port);
    server.sin_addr.s_addr = inet_addr(target_ip.c_str());
    if (connect(sock, (sockaddr *)&server, sizeof(server)) < 0)
    {
        std::cerr << "connect fail" << std::endl;
        exit(3);
    }
    std::cout << "connect success" << std::endl;
    while (true)
    {
        std::cout << "请输入："  ;
        std::getline(std::cin, line);
        if (line == "quit")
        {
            std::cout << "client quit" << std::endl;
            break;
        }
        send(sock, line.c_str(), line.size(), 0);
        char buff[1024];
        ssize_t n = recv(sock, buff, sizeof(buff), 0);
        if (n > 0)
        {
            buff[n] = 0;
            std::cout << "client echo:" << buff << std::endl;
        }
        else if (n == 0)
        {
            break;
        }

    }
    close(sock);

    return 0;
}
